<template>
  <el-dropdown trigger="click" ref="dropdownRef">
    <span class="avatar-dropdown">
      <el-icon size="30"><Avatar /></el-icon>
      <!-- <img class="user-avatar" src="@/assets/avatar.jpg" alt="avatar" /> -->
      <div class="user-name fontPorscheNextRegular">
        {{ userName }}
        <svg-icon name="arrowDown" color="#535457" />
      </div>
    </span>
    <template #dropdown>
      <el-dropdown-menu class="dropdown-menu fontPorscheNextRegular">
        <div class="dropdown-wrapper">
          <header>
            <div class="user-info">
              <strong>{{ userName }}</strong>
              <span>{{ userRole }}</span>
            </div>
            <div class="user-dealer">{{ userDealerStore }}</div>
          </header>
          <footer>
            <el-button @click="handleLogout">{{ t('navbar.logOut') }}</el-button>
          </footer>
        </div>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script>
export default {
  name: 'Avatar',
};
</script>

<script setup>
import { ref, reactive, computed } from 'vue';
import { useStore } from 'vuex';
import { ElMessageBox } from 'element-plus';
import { Avatar, UserFilled } from '@element-plus/icons-vue';
import { setting } from '@/config/setting';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';

const { title, recordRoute } = setting;
const { t } = useI18n();
const store = useStore();
const router = useRouter();

const dropdownRef = ref();
const roleInfo = reactive({});

const roleItemId = computed(() => {
  return store.getters['user/roleItemId'];
});

const userName = computed(() => {
  return  '管理员';
});

const userRole = computed(() => {
  return '';
});

const userDealerStore = computed(() => {
  let curName = '';
  return curName;
});

const roleList = computed(() => {
  return []
});

const selectRole = (data) => {
  store.dispatch('user/setRoleItemId', data.__id);
  Object.assign(roleInfo, data);
};

// 获取权限列表
const fetchPerms = async (roleId) => {
  try {
    const res = await getPermList({ roleId });
    if (res.data && Array.isArray(res.data)) {
      await store.dispatch('routes/setRouteFlag', false);
      await store.dispatch('routes/clearRoutes');
      await store.dispatch('user/setUserPermList', res.data);
    }
  } catch (err) {
    console.error(err);
  }
};

// 切换角色
const changeRole = async () => {
  dropdownRef.value.handleClose();
  if (Object.keys(roleInfo).length > 0) {
    store.dispatch('user/setUserRoleInfo', roleInfo);
    store.dispatch('common/setStoreId', roleInfo.dealerStoreCode);
    await fetchPerms(roleInfo.roleId);
  }
  router.replace('/');
  setTimeout(() => {
   window.location.reload();
  }, 100);
};

// 退出登录
const handleLogout = () => {
  ElMessageBox({
    title: t('confirm.title'),
    message: `${t('confirm.msg')}${title}？`,
    showCancelButton: true,
    confirmButtonText: t('btn.confirm'),
    cancelButtonText: t('btn.cancel'),
    dangerouslyUseHTMLString: true,
    autofocus: false,
  })
    .then(async () => {
      await store.dispatch('user/logout');
      await store.dispatch('routes/clearRoutes');
      if (recordRoute) {
        const { fullPath } = router.currentRoute._value;
        router.push({
          path: '/login',
          query: {
            redirect: fullPath,
          },
        });
      } else {
        router.push('/login');
      }
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
.avatar-dropdown {
  display: flex;
  align-content: center;
  align-items: center;
  justify-content: center;
  justify-items: center;
  height: $base-avatar-dropdown-height;
  padding: $base-padding-10;
  &:focus-visible {
    outline: none;
  }
  .user-avatar {
    width: $base-avatar-widht;
    height: $base-avatar-height;
    cursor: pointer;
    border-radius: $base-border-radius-circle;
  }
  .user-name {
    position: relative;
    margin-left: $base-margin-5;
    margin-left: $base-margin-5;
    cursor: pointer;
    color: $base-color;
  }
}
.dropdown-menu {
  overflow: hidden;
  padding: 0;
  width: auto;
}
.dropdown-wrapper {
  padding: 20px;
  min-width: 210px;
  background-color: #f7f8fa;
  header {
    border-bottom: 1px solid #d8d8d8;
    padding-bottom: 10px;
    margin-bottom: 10px;
    .user-info {
      strong {
        font-size: 16px;
      }
      span {
        margin-left: 12px;
        color: #949598;
      }
    }
    .user-dealer {
      margin-top: 5px;
      color: #6b6d70;
      font-size: 12px;
    }
  }
  .role-list {
    padding-left: 0;
    list-style: none;
    max-height: 300px;
    overflow-y: auto;
    @include base-scrollbar;
    li {
      margin-top: 8px;
      cursor: pointer;
      display: flex;
      justify-content: space-between;
      align-items: center;
      white-space: nowrap;
      .check-icon {
        margin-left: 8px;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        border: 1px solid #d8d8d8;
        background-color: #fff;
      }
      .svg-icon {
        margin-left: 8px;
      }
    }
  }
  footer {
    display: flex;
    flex-direction: column;
    margin-top: 20px;
    .el-button {
      margin-left: 0;
      &:last-child {
        margin-top: 12px;
      }
    }
  }
}
</style>
